<template>
  <div class="mapbox-maps">
    <div id="map"></div>
  </div>
</template>

<script>
import mapboxgl from "mapbox-gl";
import "mapbox-gl/dist/mapbox-gl.css";
export default {
  props: ["coordinate", "mapurl"],
  data() {
    return {
      map: null,
      markers: null,
      markerCoordinates: {},
      showMenu: false,
      menuTop: 0,
      menuLeft: 0,
      selectedMarker: null,

    };
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      if (this.map != null) {
        this.map.remove();
      }
      let mapboxglurl = this.mapurl == null ? "https://ibasemaps-api.arcgis.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}?token=Your%20apiKey" : this.mapurl
      mapboxgl.accessToken =
        "pk.eyJ1IjoieGlhb3poYW5naiIsImEiOiJjbDVwNm9zN2owdTgxM2RuemVobm51Nzd3In0.8qLyL04Wpoir1_YutPa7kw";
      this.map = new mapboxgl.Map({
        container: "map",
        style: {
          version: 8,
          sources: {
            "raster-tiles": {
              attribution: "",
              type: "raster",
              tiles: [
                mapboxglurl
              ],
              tileSize: 256,
            },
          }, "glyphs": "mapbox://fonts/mapbox/{fontstack}/{range}.pbf", // 设置字体资源链接
          layers: [
            {
              id: "simple-tiles",
              type: "raster",
              source: "raster-tiles",
              minzoom: 0,
              maxzoom: 22,
            },
          ],
        },
        center: [113, 34],
        zoom: 14,
      });
      let that = this;
      this.map.on("load", function () {
        if (that.coordinate != null && that.coordinate != "") {
          that.markerCoordinates = that.coordinate.split(",");
          that.marker = new mapboxgl.Marker()
            .setLngLat({
              lat: that.markerCoordinates[1],
              lng: that.markerCoordinates[0],
            })
            .addTo(that.map);
          that.map.setCenter([
            that.markerCoordinates[0],
            that.markerCoordinates[1],
          ]);
        }
        that.loadinit();
      });

      this.map.on("click", (e) => {
        if (this.marker != null) {
          this.marker.remove();
        }
        this.markerCoordinates = [e.lngLat.lng, e.lngLat.lat];
        this.marker = new mapboxgl.Marker().setLngLat(e.lngLat).addTo(this.map);
        this.$emit("selectmarker", this.markerCoordinates);
      });
    },
    loadinit() {
      let $this = this
      function addImageSource() {
        const images = [
          "/temp/cheliang.png",
          "/temp/chukunum.png",
          "/temp/churuku.png",
          "/temp/dadou.png",
          "/temp/dami.png",
          "/temp/qita.png",
          "/temp/shiyongyou.png",
        ];
        const imageNames = ["1", "2", "3", "4", "5", "6", "greenMarker"];
        images.forEach((item, index) => {
          $this.map.loadImage(item, (error, image) => {
            if (error) throw error;
            $this.map.addImage(imageNames[index], image);
          });
        });
      }
      addImageSource();
      // 随机造数据
      const geojson = {
        type: "FeatureCollection",
        features: [],
      };
      for (let i = 0; i < 100; i++) {
        geojson.features.push({
          type: "Feature",
          properties: {
            type: 1 + Math.floor(Math.random() * 5),
          },
          geometry: {
            type: "Point",
            coordinates: [110 + Math.random() * 10, 30 + Math.random() * 10],
          },
        });
      }
      // 添加source
      this.map.addSource("cluster", {
        type: "geojson",
        data: geojson,
        cluster: true,
        clusterRadius: 30,
      });
      // 添加layer
      this.map.addLayer({
        id: "cluster",
        type: "symbol",
        source: "cluster",
        layout: {
          "icon-size": ["case", ["has", "point_count"], 0.5, 0.3],
          "icon-image": [
            "case",
            ["has", "point_count"],
            "greenMarker",
            ["get", "type"],
          ],

          'text-field': ['to-string', ['get', 'point_count']], // 使用表达式动态计算并显示聚合数量
          "text-offset": [0, 0],
          "text-size": 20,
          "icon-ignore-placement": true,
        },
        paint: {
          "text-color": "#F0F0F0",
          "text-halo-width": 0.5,
          "text-halo-color": "#F0F0F0",
        },
      });
    }
  },
};
</script>
<style>
/* 隐藏mapbox商标 */
.mapboxgl-ctrl-logo {
  display: none !important;
}
</style>
<style scoped>
.mapbox-maps {
  width: 100%;
  height: calc(100vh - 170px);
  position: relative;
}

#map {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}

.mapboxgl-canvas {
  outline: none;
}
</style>
